/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://github.com/mineadmin
 */
import type { MaProTableColumns, MaProTableExpose } from "@mineadmin/pro-table";
import type { UseDialogExpose } from "@/hooks/useDialog.ts";

import defaultAvatar from "@/assets/images/defaultAvatar.jpg";
import { ElTag, ElImage } from "element-plus";
import { useMessage } from "@/hooks/useMessage.ts";
import { ResultCode } from "@/utils/ResultCode.ts";
import hasAuth from "@/utils/permission/hasAuth.ts";
import { deleteByIds } from "$/attractions/commerce/api/commerceEnergy.ts";
import { page as merchantPage } from "$/attractions/commerce/api/commerceMerchant.ts";

export default function getTableColumns(
  dialog: UseDialogExpose,
  formRef: any,
  t: any
): MaProTableColumns[] {
  const msg = useMessage();

  const merchantList = ref<any[]>([]);

  onMounted(async () => {
    const res2 = await merchantPage({
      page: 1,
      pageSize: 1000,
    });
    if (res2.code === 200 && res2.data && res2.data.list) {
      merchantList.value = res2.data.list;
    }
  });

  return [
    {
      type: "selection",
      showOverflowTooltip: false,
      label: () => t("crud.selection"),
    },
    {
      label: "商户名称",
      prop: "merchant_id",
      cellRender: ({ row }) => {
        const merchantName = merchantList.value.find(
          (merchant) => merchant.id === row.merchant_id
        );
        return merchantName?.merchant_name || `商户名称${row.merchant_id}`;
      },
    },
    {
      label: "费用类型",
      prop: "cost_type",
      cellRender: ({ row }) => {
        const costType = {
          1: "水费",
          2: "电费",
          3: "气费",
          4: "其他",
        };
        return costType[row.cost_type] || `费用类型${row.cost_type}`;
      },
    },
    { label: "用量", prop: "cost_usage" },
    { label: "单价", prop: "cost_price" },
    { label: "表读数", prop: "cost_meter_reading" },
    { label: "总费用", prop: "total_amount" },
    { label: "缴费日期", prop: "payment_date", mode: "date", showTime: false },
    {
      label: "付款方式",
      prop: "payment_method",
      cellRender: ({ row }) => {
        const statusMap = {
          1: { text: "银行转账", type: "success" },
          2: { text: "微信支付", type: "warning" },
          3: { text: "支付宝支付", type: "info" },
          4: { text: "现金", type: "danger" },
          5: { text: "其他付款方式", type: "info" },
        };
        const status = statusMap[row.payment_method] || {
          text: "未知",
          type: "info",
        };
        return h(ElTag, { type: status.type }, () => status.text);
      },
    },
    { label: "发票号", prop: "invoice_id", renderProps: { multiple: false } },
    { 
      label: "抄表照片", 
      prop: "meter_photos",
      cellRender: ({ row }) => {
        if (!row.meter_photos) {
          return h('span', { style: { color: '#999' } }, '暂无图片');
        }
        
        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl = env.VITE_OPEN_PROXY === 'true' ? env.VITE_PROXY_PREFIX : env.VITE_APP_API_BASEURL;
        const imageUrl = `${baseUrl}${row.meter_photos}`;
        
        return h(ElImage, {
          src: imageUrl,
          alt: '抄表照片',
          style: {
            width: '60px',
            height: '40px',
            borderRadius: '4px',
            border: '1px solid #ddd'
          },
          fit: 'cover',
          previewSrcList: [imageUrl],
          previewTeleported: true,
          onError: () => {
            console.warn('抄表照片加载失败:', imageUrl);
          }
        }, {
          error: () => h('div', {
            style: {
              width: '60px',
              height: '40px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#f5f5f5',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '12px',
              color: '#999'
            }
          }, '加载失败')
        });
      }
    },
    { 
      label: "账单照片", 
      prop: "bills_photos",
      cellRender: ({ row }) => {
        if (!row.bills_photos) {
          return h('span', { style: { color: '#999' } }, '暂无图片');
        }
        
        // 获取API基础URL
        const env = import.meta.env;
        const baseUrl = env.VITE_OPEN_PROXY === 'true' ? env.VITE_PROXY_PREFIX : env.VITE_APP_API_BASEURL;
        const imageUrl = `${baseUrl}${row.bills_photos}`;
        
        return h(ElImage, {
          src: imageUrl,
          alt: '账单照片',
          style: {
            width: '60px',
            height: '40px',
            borderRadius: '4px',
            border: '1px solid #ddd'
          },
          fit: 'cover',
          previewSrcList: [imageUrl],
          previewTeleported: true,
          onError: () => {
            console.warn('账单照片加载失败:', imageUrl);
          }
        }, {
          error: () => h('div', {
            style: {
              width: '60px',
              height: '40px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#f5f5f5',
              border: '1px solid #ddd',
              borderRadius: '4px',
              fontSize: '12px',
              color: '#999'
            }
          }, '加载失败')
        });
      }
    },
    {
      type: "operation",
      fixed: "right",
      label: () => t("crud.operation"),
      operationConfigure: {
        actions: [
          {
            name: "edit",
            icon: "material-symbols:person-edit",
            show: ({ row }) => hasAuth("commerce_energy:commerceEnergy:update"),
            text: () => t("crud.edit"),
            onClick: ({ row }) => {
              dialog.setTitle(t("crud.edit"));
              dialog.open({ formType: "edit", data: row });
            },
          },
          {
            name: "del",
            icon: "mdi:delete",
            text: () => t("crud.delete"),
            show: ({ row }) => hasAuth("commerce_energy:commerceEnergy:delete"),
            onClick: ({ row }, proxy: MaProTableExpose) => {
              msg.delConfirm(t("crud.delDataMessage")).then(async () => {
                const response = await deleteByIds([row.id]);
                if (response.code === ResultCode.SUCCESS) {
                  msg.success(t("crud.delSuccess"));
                  proxy.refresh();
                }
              });
            },
          },
        ],
      },
    },
  ];
}
